    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>动画封装之div滑动</title>
        <style type="text/css">
            *{
                margin:0;
                padding: 0;
            }
            button{
                margin-left: 20px;
                margin-top: 10px;
                margin-bottom: 10px;
            }
            #big{
                background-color: #cccccc;
                width: 800px;
                height: 300px;
                position: relative;
            }
            #child{
                height: 100px;
                width: 100px;
                background-color: #990099;
                position: absolute;
                top:40px;
            }
            #child1{
                height: 100px;
                width: 100px;
                background-color: #32ff42;
                position: absolute;
                top:150px;
            }
        </style>
    </head>
    <body>
    <div id="big">
        <button>移动到200</button>
        <button>移动到500</button>
        <div id="child"></div>
        <br>
        <div id="child1"></div>
    </div>
    <script>
        //需求：1.点击200按钮块缓慢移动到指定位置
        //     2.点击400按钮块缓慢移动到指定位置
        //     3.200按钮与400按钮切换时候可以切换过来
        //1.寻找事件源，绑定事件
        var btn1=document.getElementsByTagName("button")[0];
        var btn2=document.getElementsByTagName("button")[1];
        var chld=document.getElementById("child");
        var chld1=document.getElementById("child1");
        var timer=null;
        btn1.onclick=function () {
            animate(200,chld);
        };
        btn2.onclick=function () {
            animate(500,chld1);
        };

        function animate(pace,func) {
            clearInterval(timer);
            var speed=0;
            if (func.offsetLeft<pace){
              speed=5;
            }else {
                speed=-5;
            }
            timer=setInterval(function () {
                func.style.left=func.offsetLeft+speed+"px";
                var distance=pace-func.offsetLeft;
                if (Math.abs(distance)<=5){
                    clearInterval(timer);
                    func.style.left=pace+"px";
                }
            },30);
        }
    </script>
    </body>
    </html>